# PC端后端启动程序
import json
import os
import sys
 
import traceback
from flask import Flask, request, render_template, send_from_directory
from flask_cors import CORS

import utilsapp.common 

sys.path.append('.')
from utilsapp.logger import add_log
from apps.tasks.task_main import task_index

from approute import reg_route, create_db_pool, before_request

app = Flask(import_name=__name__, static_url_path='/templates', static_folder='templates', template_folder='templates')
app.config['JSON_AS_ASCII'] = False
app.secret_key = '123456'

reg_route(app)

CORS(app)


# 定义处理所有未捕获异常的函数
@app.errorhandler(Exception)
def handle_exception(e):
    traceback.print_exc()
    error_message = traceback.format_exc()
    add_log(str(e), error_message)
    return {"code": -1, 'msg': '请求异常', 'data': [], 'error': str(e)}


@app.before_request
def before():
    res = before_request(app)
    if res['code'] != 0:
        return res


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/upload/<path:filename>')
def upload(filename):
    return send_from_directory(os.getcwd() + '/upload/', filename, conditional=True)


@app.route('/static/<path:filename>')
def upload_static(filename):
    return send_from_directory(os.getcwd() + '/static/', filename, conditional=True)


# 自定义404错误处理函数
@app.errorhandler(404)
def page_not_found(e):
    if 'api' in request.full_path:
        return {"code": 404, "msg": f"路径不存在{request.full_path}"}
    return render_template('index.html')


def run():
    with open("./config.json", "r", encoding="utf-8") as f:
        settings = json.load(f)
        ieplatkey = settings['ieplatkey']
        try:
            with open("ieplat.key", "r", encoding="utf-8") as f:
                ieplatkey = f.read()
        except:
            pass

        try:
            with open("./mysql.json", "r", encoding="utf-8") as f:
                settings['mysql'] = json.load(f)
        except:
            pass

        flag = utilsapp.common.check_code(ieplatkey)
        if not flag[0]:
            print('授权失败,已停止运行')
            return
        settings['app_auth'] = flag[1]
        app.config['settings'] = settings

        pinfo = utilsapp.common.get_process_using_port(settings['webapi-host'])
        if pinfo:
            print(f'启动失败,{settings["webapi-host"]}端口已被进程PID:{pinfo.pid}占用,已停止运行')
            # return

        print('当前配置文件参数:', settings)
        print('当前MQTT参数:', settings['mqtt'])
    # # 当你需要验证用户名和密码时，请设置该项
    # app.config['QL参数:', settings['mysql'])
    # app.config['MQTT_BROKER_URL'] = settings['mqtt']["host"]
    # app.config['MMQTT_USERNAME'] = settings['mqtt']["username"]
    # # 当你需要验证用户名和密码时，请设置该项
    # app.config['MQTT_PASSWORD'] = settings['mqtt']["password"]
    # CORS(app)
    # mqtt_client = Mqtt(app)

    app.add_log = add_log
    create_db_pool(app)
    if os.environ.get('WERKZEUG_RUN_MAIN') is None:
        task_index(app)
    is_debug = os.environ.get('ENVIRONMENT') == '1'
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None
    app.run(host=app.config['settings']['webapi-ip'], port=app.config['settings']['webapi-host'], debug=is_debug)


if __name__ == '__main__' or __name__ == 'main':
    try:
        run()
        if getattr(sys, 'frozen', False):
            input()
    except Exception as e:
        traceback.print_exc()
        print('程序启动异常,已停止运行')
        if getattr(sys, 'frozen', False):
            input()
